package mobileann.mafamily.utils.code;

import java.io.File;
import java.util.Hashtable;

import mobileann.mafamily.act.main.FS;
import mobileann.mafamily.utils.SPUtils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import android.R.integer;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.DisplayMetrics;
import android.widget.ImageView;

public class CodeUtils {
	public static String URL="http://www.mobileann.com";// 摩安网页地址
	private static CodeUtils _instance=null;
	private Context context;
	public static CodeUtils getInstance(Context context){
		if(_instance==null){
			_instance=new CodeUtils(context);
		}
		return _instance;
	}
	public CodeUtils(Context context){
		this.context=context;
	}
	/*
	 * 生成二维码
	 */
	public synchronized Bitmap qr_code(BarcodeFormat format)
			throws WriterException {
		MultiFormatWriter writer = new MultiFormatWriter();
		Hashtable<EncodeHintType, String> hst = new Hashtable<EncodeHintType, String>();
		hst.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		BitMatrix matrix = writer.encode(getQRCode(), format,(int) ( 432*getScreenDensity(context)), (int) ( 432*getScreenDensity(context)), hst);
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		int[] pixels = new int[width * height];
		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				if (matrix.get(x, y)) {
					pixels[y * width + x] = 0xff000000;
				}

			}
		}
		Bitmap bitmap = Bitmap.createBitmap(width, height,
				Bitmap.Config.ARGB_8888);
		// 通过像素数组生成bitmap,具体参考api
		bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
		return bitmap;
	}

	/*
	 * 产生二维码的字符串
	 */
	public synchronized String getQRCode() {
//		String url = "http://www.mobileann.com/";
		String userID = FS.getInstance().self().getUid();// 自己的id（手机号）
		int userRole = FS.getInstance().self().getRole();// 自己的角色
		String nickName = FS.getInstance().self().getNickname();// 自己的昵称
		String contents = URL+File.separator + userID +File.separator + userRole+ File.separator + nickName ;
		return contents;
	}

	public synchronized float getScreenDensity(Context context) {
		// 获取屏幕密度
		DisplayMetrics dm = new DisplayMetrics();
		dm = context.getResources().getDisplayMetrics();
		float density = dm.density; // 屏幕密度（像素比例：0.75/1.0/1.5/2.0）
		int densityDPI = dm.densityDpi; // 屏幕密度（每寸像素：120/160/240/320）
		return density;
	}
}
